package com.snow.common.interceptor;

import com.snow.common.base.CommonConstant;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 * All rights Reserved, Designed By www.cusc.com
 *
 * @author yanke
 * @Title: MdcInterceptHandler
 * @Package com.snow.common.interceptor
 * @Description:类描述
 * @Email yanke@cu-sc.com
 * @version: v1.0.0
 * @date: 2021/5/17/0017 9:46
 * @Copyright: 2021  www.faw.com.cn Inc. All rights reserved. <br/>
 * Modification History:<br/>
 * Date         Author          Version            Description<br/>
 * *---------------------------------------------------------*<br/>
 * 2021/5/17/0017     Administrator           v1.0.0               修改原因<br/>
 * @since JDK 1.8
 */
@Slf4j
@Component
public class MdcInterceptHandler implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestid = request.getHeader("REQUESTID");
//        log.info("这是HandlerInterceptor");
        if (Objects.isNull(requestid)) {
            String uuid = UUID.randomUUID().toString();
            MDC.put(CommonConstant.REQUESTID, uuid);
            log.info(MDC.get(CommonConstant.REQUESTID));
        } else {
            MDC.put(CommonConstant.REQUESTID, requestid);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove(CommonConstant.REQUESTID);
    }
}
